<template>
  <el-dialog append-to-body :title="title" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" :visible.sync="visible" :width="'480px'">
    <el-form label-width="100px" size="small" @submit.native.prevent>
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="部门名称" required>
            <el-input size="small" v-model.trim="name" placeholder="请输入部门名称" maxlength="30" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="submitLoading" @click="cancel()">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="validForm()">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { UpdateDepartmentItemName } from '@/views/user-management/services/index';
export default {
  props: ['visible', 'title', 'node'],
  data() {
    return {
      name: '',
      submitLoading: false
    }
  },
  watch: {
    node: {
      immediate: true,
      handler(newValue) {
        if (!newValue) return;
        this.name = newValue.name;
      }
    }
  },
  methods: {
    cancel() {
      this.closeModel();
      this.name = this.node.name;
    },
    closeModel() {
      this.$emit('update:visible', false);
    },
    validForm() {
      if (!this.name) {
        this.$message.warning('请输入部门名称!');
        return;
      }
      this.submitLoading = true;
      UpdateDepartmentItemName({
        id: this.node.id,
        name: this.name,
        parentId: this.node.parentId
      })
      .then(success => {
        this.submitLoading = false;
        if (success.code == 200) {
          this.$message.success(`${this.title}成功!`);
          this.closeModel();
          this.$emit('update', this.name);
        } else {
          this.$message.error(`${this.title}失败!`);
        }
      })
      .catch(error => {
        this.submitLoading = false;
        this.$message.error(error);
      })
    }
  }
}
</script>
